package service

import (
	"errors"
	"log"

	"todolist/internal/model"
	"todolist/internal/repository"
	"todolist/pkg/auth"
)

type UserService struct {
    userRepo *repository.UserRepository
}

func NewUserService(userRepo *repository.UserRepository) *UserService {
    return &UserService{userRepo: userRepo}
}

func (s *UserService) Register(username, password string) (*model.User, error) {
    // 检查用户名是否已存在
    existingUser, err := s.userRepo.FindByUsername(username)
    if err == nil && existingUser != nil {
        return nil, errors.New("username already exists")
    }

    user := &model.User{
        Username: username,
        Password: password, // 实际应用中应该加密
    }

    if err := s.userRepo.Create(user); err != nil {
        return nil, err
    }

    return user, nil
}

func (s *UserService) Login(username, password string) (string, *model.User, error) {
    log.Printf("Attempting login for user: %s", username)
    
    user, err := s.userRepo.FindByUsername(username)
    if err != nil {
        log.Printf("Error finding user: %v", err)
        return "", nil, errors.New("invalid credentials")
    }

    if user.Password != password {
        log.Printf("Password mismatch for user: %s", username)
        return "", nil, errors.New("invalid credentials")
    }

    token, err := auth.GenerateToken(user.ID)
    if err != nil {
        log.Printf("Error generating token: %v", err)
        return "", nil, err
    }

    log.Printf("Login successful for user ID: %d", user.ID)
    return token, user, nil
} 